<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/5/7
 * Time: 下午5:12
 */

namespace backend\controllers;

use common\helpers\predis\Predis;
use common\service\VoteService;
use yii;
use common\service\ActivityCategoryService;
use common\service\BrandService;
use common\service\CouponCategoryService;
use common\service\ProductService;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;

class CacheController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ],
            ]
        ];
    }

    public function actionDelete()
    {
        $keyArr = $this->getCacheKeyArr();
        foreach ($keyArr as $key) {
            $keys = Predis::getInstance()->getClient()->client->keys($key);
            if (!empty($keys)) {
                Predis::getInstance()->getClient()->client->del($keys);
            }
        }
        Yii::$app->session->addFlash("success", '缓存已清除');
        return $this->redirect(['brand/index']);
    }

    private function getCacheKeyArr()
    {
        return [
            ActivityCategoryService::getCategoryBySymbolCacheKey("*"),
            ActivityCategoryService::getListCacheKey(),
            ActivityCategoryService::getCategoryByIdCacheKey("*"),
            BrandService::getListCacheKey(),
            BrandService::getBrandCacheKey("*"),
            CouponCategoryService::getListCacheKey(),
            CouponCategoryService::getCategoryCacheKey("*"),
            ProductService::getListCacheKey("*"),
            ProductService::getBrandCacheKey("*"),
            CouponCategoryService::getListCacheKey(),
            CouponCategoryService::getCategoryCacheKey("*"),
            "actionPrizeList"
        ];
    }

    public function actionDelVoteCache()
    {
        $keyArr = [
            VoteService::getShareCountCacheKey("*", "*"),
            VoteService::getVoteCacheKey("*", "*"),
            VoteService::getShareCacheKey("*")
        ];
        foreach ($keyArr as $key) {
            $keys = Predis::getInstance()->getClient()->client->keys($key);
            if (!empty($keys)) {
                Predis::getInstance()->getClient()->client->del($keys);
            }
        }
        Yii::$app->session->addFlash("success", '缓存已清除');
        return $this->redirect(['brand/index']);
    }
}
